var app = getApp()
const LAST_CONNECTED_DEVICE = 'last_connected_device'

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(',')
}

function str2ab(str) {
  // Convert str to ArrayBuff and write to printer
  let buffer = new ArrayBuffer(str.length)
  let dataView = new DataView(buffer)
  for (let i = 0; i < str.length; i++) {
    dataView.setUint8(i, str.charAt(i).charCodeAt(0))
  }
  return buffer;
}
var m =0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay:false,//是否播放
    lastDevice:[],
    devices: [],
    mydevice: [],
    connectdeviceId:'',
    modearray:["A1","A2","B1","B2","C1","C2"],
    mode:'A1',
    notify:'',
    connected: false,
    chs:[],
  },
  onLoad(options) {
   
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   var that = this;
    var lastDevice = wx.getStorageSync(LAST_CONNECTED_DEVICE);
   
    if(lastDevice){
     let index = lastDevice.indexOf(':');  
     let deviceId = lastDevice.substring(index + 1, lastDevice.length);
      this.setData({
        connectdeviceId: deviceId
      }) 
    }

    let connected = getApp().globalData.connected
    console.log("onshow connected", connected)
    if (connected){   
      getApp().globalData.connected = false;
      wx.showToast({
        title: '准备重连蓝牙',
      }) 
    //  setTimeout(function () {
    //    that.closeBLEConnection()   //断开连接    
    //  }, 1000) //延迟时间 
    }

    this.setData({
      lastDevice: lastDevice,
    })
   
    if (lastDevice && !this.data.connected){     
      setTimeout(function () {
        that.createBLEConnectionWithDeviceId(lastDevice)  //连接蓝牙 
      },2000) //延迟时间  
    }

  },
  connecte:function(){
    wx.showToast({
      title: '连接蓝牙',
    })
    if(this.data.connected){
      this.closeBLEConnection()
    }else{
      var lastDevice = wx.getStorageSync(LAST_CONNECTED_DEVICE);
      this.createBLEConnectionWithDeviceId(lastDevice)
    }
   
  },
    // 添加设备
    addDevice(){
    
      wx.navigateTo({
        url: '/pages/device/index',
      })

    },
  // 选择模式
  changeMode(e){
    let type = e.currentTarget.dataset.type;
    if(type == 'plus' && m < 5) m++;
    if(type == 'minus' && m > 0) m--;
    console.log(m);
    this.setData({
      mode:this.data.modearray[m]
    })

    if(this.data.connected){
        if (this.data.modearray[m] == "A1") {
          var hex = "fe5aa50105"; //发送启动命令默认A1
        }
        if (this.data.modearray[m] == "A2") {
          var hex = "FE5A2100000002000000070C"; //发送A2模式，2mm,7秒
        }
        if (this.data.modearray[m] == "B1") {
          var hex = "FE5A2100000004000000100C"; //发送B1模式，4mm,10秒
        }
        if (this.data.modearray[m] == "B2") {
          var hex = "FE5A2100000004000000140C"; //发送B2模式，4mm,14秒
        }
        if (this.data.modearray[m] == "C1") {
          var hex = "FE5A2100000008000000200C"; //发送C2模式，8mm,20秒
        }
        if (this.data.modearray[m] == "C2") {
          var hex = "FE5A2100000008000000280C"; //发送C2模式，8mm,28秒
        }
        var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        }))
        var buffer = typedArray.buffer
        this._writeBLECharacteristicValue(buffer)
    } else {
      wx.showToast({
        title: '蓝牙未连接',
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
      fail: (res) => {
        console.log('startBluetoothDevicesDiscovery fail', res)
      }
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      complete: () => {
        console.log('stopBluetoothDevicesDiscovery')
        this._discoveryStarted = false
      }
    })
  },
  //查找蓝牙设备
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {

      console.log("device", res);

      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (device.name == 'MyopicTherapy') {
          //排除其它蓝牙设备
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}
          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }
          this.setData(data)
        }
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    this._createBLEConnection(deviceId, name)
    //let mydevice = [{ deviceId: deviceId, name: name }, { deviceId: deviceId, name: name }];
   // wx.setStorageSync("mydevice", mydevice)
  },
  _createBLEConnection(deviceId, name) {
  
    wx.showLoading()
    wx.createBLEConnection({
      deviceId,
      success: () => {
        console.log('createBLEConnection success');
        this.setData({
          connected: true,
          name,
          deviceId,
        })
       
        this.getBLEDeviceServices(deviceId)
        wx.setStorage({
          key: LAST_CONNECTED_DEVICE,
          data: name + ':' + deviceId
        })
        wx.hideLoading()  
        wx.showToast({
          title: '蓝牙连接成功',
        })
      },
      complete() {
           
      },
      fail: (res) => {
        if (res.errCode==10012){
          this.setData({
            connected: false
          })
        }
        wx.hideLoading()  
        wx.showToast({
          title: '蓝牙连接失败',
        })
        console.log('createBLEConnection fail', res)
      }
    })

    this.stopBluetoothDevicesDiscovery()
  },
  //断开连接
  closeBLEConnection(deviceId) {
    var that =this;
    if(this.data.connected){
      this.writeBLECharacteristicValueStop()
      setTimeout(function () {
        wx.closeBLEConnection({
          deviceId: that.data.connectdeviceId
        })
        wx.showToast({
          title: '断开蓝牙',
        })
      }, 2000) //延迟时间 
    }else{
      var lastDevice = wx.getStorageSync(LAST_CONNECTED_DEVICE);
      this.createBLEConnectionWithDeviceId(lastDevice)
    }
   
   
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  //获取服务
  getBLEDeviceServices(deviceId) {

    var that = this;
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log('getBLEDeviceServices', res)
        console.log('getBLEDeviceServices_canread', res.services[1].uuid)
       // this._readBLECharacteristicValue(res.services[2].uuid, deviceId);

        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid) //获取写服务特征值
            this.getBLEDevicenotifyCharacteristics(deviceId, res.services[i].uuid)//获取通知服务特征值并开启通知
            return
          }
        }
      }
    })

  },

  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        // 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
        // 只能一个个去试
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid

            break;
          }
        }

      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
  },
  //开启notify
  getBLEDevicenotifyCharacteristics: function (deviceId, serviceId){ 
   var that= this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        // 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
        // 只能一个个去试
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
          if (item.properties.notify) {
               
          wx.notifyBLECharacteristicValueChange({
            state: true, // 启用 notify 功能
            deviceId: deviceId,//蓝牙设备id
            serviceId: serviceId,//服务id
            characteristicId: item.uuid,//服务特征值indicate
            success: function (res) {
             
              console.log('开启notify', res.errMsg)
              //监听低功耗蓝牙设备的特征值变化
              wx.onBLECharacteristicValueChange(function (res) {
                that.setData({
                  notify:ab2hex(res.value)
                })
                console.log('开启通知后特征值变化', ab2hex(res.value));
               
              })
           
            },
            fail(res) {
              console.log('开启notify失败', res)
            }
          });




            break;
          }
        }


      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })


    

  },
  noconnected:function(){
    wx.showToast({
      title: '设备未连接',
    })
  },
  writeBLECharacteristicValueStart:function() {
      this.setData({
        isPlay: true
      })
    
      var hex = "fe5aa50105"; //发送启动命令默认A1
    
      var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
      }))
     
      var buffer = typedArray.buffer    
      this._writeBLECharacteristicValue(buffer,1) //1启动 2停止
  
  },
  writeBLECharacteristicValueStop:function() {
      this.setData({
        isPlay: false
      })
      var hex = "fe5aa50205"; //发送停止命令
      var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
      }))
      console.log(typedArray)
      var buffer = typedArray.buffer     
      this._writeBLECharacteristicValue(buffer,2)   //1启动 2停止
  },

  //写
  _writeBLECharacteristicValue(buffer,start_or_stop) {
    var that =this;
    let deviceinfo = wx.getStorageSync('deviceinfo');

    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
      success(res) {

        if (start_or_stop==1){
          //蓝牙设备启动训练写入远端数据库
          app.post('exercise/save', { bluetooth_id: that._deviceId}).then(res => {
            console.log("start_id", res.data.id)
            wx.setStorageSync("trainid", res.data.id)
          })
          wx.showToast({
            title: '启动训练成功',
          })
        }
        if (start_or_stop==2){
         
          //蓝牙设备停止训练写入远端数据库
          app.post('exercise/save', { id: wx.getStorageSync("trainid") }).then(res => {
          console.log("stop", res)
          })
          wx.showToast({
            title: '停止训练成功',
          })
        }

       
       // console.log('writeBLECharacteristicValue success', res)
        return true;
      },
      fail(res) {
       wx.showToast({
          title: res.errMsg,
         icon:"none"
       })
        console.log('writeBLECharacteristicValue fail', res.errMsg)
        return false;
      }
    })


    // this._readBLECharacteristicValue();
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },

  //读
  _readBLECharacteristicValue: function (serviceId, deviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        // 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
        // 只能一个个去试
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]

          if (item.properties.read) {

            wx.readBLECharacteristicValue({
              deviceId: deviceId,
              serviceId: serviceId,
              characteristicId: item.uuid,
              success(res) {

                console.log('readBLECharacteristicValue success', res)
              },
              fail(res) {

                console.log('readBLECharacteristicValue fail', res)
              }
            })


            this.setData({
              canRead: true
            })
            this._deviceId = deviceId
            this._serviceIdRead = serviceId
            this._characteristicIdRead = item.uuid



            break;
          }
        }




      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })


  },

  createBLEConnectionWithDeviceId(e) {
    // 小程序在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备
    //const device = this.data.lastDevice
    const device = e;
    if (!device) {
      return
    }
    const index = device.indexOf(':');
    const name = device.substring(0, index);
    const deviceId = device.substring(index + 1, device.length);
    console.log('createBLEConnectionWithDeviceId', name + ':' + deviceId)
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this._createBLEConnection(deviceId, name)
      },
      fail: (res) => {
        console.log('openBluetoothAdapter fail', res)
        if (res.errCode === 10001) {
          wx.showModal({
            title: '错误',
            content: '蓝牙未开启, 请打开蓝牙后重试。',
            showCancel: false
          })
          wx.onBluetoothAdapterStateChange((res) => {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              // 取消监听
              wx.onBluetoothAdapterStateChange(() => {
              });
              this._createBLEConnection(deviceId, name)
            }
          })
        }
      }
    })
  },

  
})